import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.rosuda.REngine.REXP;
import org.rosuda.REngine.REXPLogical;
import org.rosuda.REngine.Rserve.RConnection;
import org.rosuda.REngine.Rserve.RFileOutputStream;


public class MainClass {
	
	static RConnection c;
	
	public static REXP Reval(String s) throws Exception{
		System.out.println(">>> " + s);
		return c.eval(s);
	}
	
	/**
	 * Transfers the file specified by file to the remote server and then reads it into the vector vname.
	 * The existence of the file is first checked and if override is false then the existing file is used.
	 * The override feature saves IO time if the same file is to be checked more than once (for example if the user wanted to test various delim options or later wanted to do something with the file.
	 * 
	 * @param file
	 * @param vname
	 * @param override
	 * @throws Exception 
	 */
	public static void readDelim(String file, String vname, boolean override, String delimargs) throws Exception{
		if (delimargs.equals("")){
			delimargs = "sep = \"\\t\", header = TRUE, fill = TRUE";
		}
		File clientFile = new File(file);
		
		String rfilepath = "file.path(tempdir(), \"" + clientFile.getName() + "\")";
		
		if (override || !((REXPLogical) Reval("file.exists(" + rfilepath + ")")).isTRUE()[0]){
			RFileOutputStream fos = c.createFile(clientFile.getName());
			FileInputStream fis = new FileInputStream(file);
			while (fis.available() < 5000){
				byte[] b = new byte[5000];
				fis.read(b);
				fos.write(b);
			}
			byte[] bf = new byte[fis.available()];
			fis.read(bf);
			fos.write(bf);
			fis.close();
			fos.close();
		}
		Reval(vname + "<-read.table(\"" + clientFile.getName() + "\", " + delimargs + ")");
	}
	
	private static class RLoop implements Runnable{

		@Override
		public void run() {
			String command = "C:\\Users\\Spunky\\Documents\\R\\win-library\\2.11\\Rserve\\Rserve.exe --no-save";
			try {
				Runtime.getRuntime().exec(command);
			} catch (IOException e) {
				System.out.println("Failed to load R session.");
				e.printStackTrace();
			}
			
		}
		
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println("Starting Program");
		System.out.println("Starting R Session");
		Thread t = new Thread(new RLoop());
		t.start();
		System.out.println("Done starting the R Server.");
		
		try{
			System.out.println("Starting R");
			c = new RConnection();
			System.out.println("Connection Done");
			REXP xp = c.eval("names(iris)");
			for (String s : xp.asStrings()){
				System.out.println(s);
			}
			readDelim("C:\\Users\\Spunky\\Documents\\Kyle Work\\HPRD\\GGGenes.csv", "gggenes", false, "sep = \",\", header = FALSE");
			REXP xpp = c.eval("names(gggenes)");
			for (String s : xpp.asStrings()){
				System.out.println(s);
			}
			// c.serverShutdown();
			System.out.println("Shutting down the server.");
			c.shutdown();
			System.out.println("The Server is shutdown.");
			System.out.println("Testing server shutdown.");
			REXP xppp = c.eval("names(gggenes)");
			for (String s : xppp.asStrings()){
				System.out.println(s);
			}
			c.close();
		} catch(Exception e){
			e.printStackTrace();
		}
	}

}
